<template>
    <div>
        <h1>计时器</h1>
        <button @click="startTimer" :disabled="isRunning">开始计时</button>
        <p>{{ timer }}</p>
        <button @click="stopTimer" :disabled="!isRunning">结束计时</button>
    </div>
</template>


<!-- 非语法糖 
<script>
import { ref } from 'vue';

export default {
    setup() {
        const timer = ref(0);
        const isRunning = ref(false);
        let intervalId = null;

        const startTimer = () => {
            if (!isRunning.value) {
                intervalId = setInterval(() => {
                    timer.value++;
                }, 1000);
                isRunning.value = true;
            }
        };

        const stopTimer = () => {
            if (isRunning.value) {
                clearInterval(intervalId);
                isRunning.value = false;
            }
        };

        return {
            timer,
            isRunning,
            startTimer,
            stopTimer
        };
    }
};

</script>
-->

<!-- 语法糖 -->
<script setup>
import { ref } from 'vue'

const timer = ref(0);
const isRunning = ref(false);
let intervalId = null;

const startTimer = () => {
    if (!isRunning.value) {
        intervalId = setInterval(() => {
            timer.value++;
        }, 1000);
        isRunning.value = true;
    }
};

const stopTimer = () => {
    if (isRunning.value) {
        clearInterval(intervalId);
        isRunning.value = false;
    }
};

</script>